<template>
  <view class="container">
    <!-- 商品图片轮播 -->
    <swiper class="product-swiper" circular :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000">
      <swiper-item v-for="(item, index) in productInfo.images" :key="index">
        <image :src="item" mode="aspectFill"></image>
      </swiper-item>
    </swiper>
    
    <!-- 商品信息 -->
    <view class="product-info">
      <view class="price-section">
        <text class="price">¥{{productInfo.price}}</text>
        <text class="original-price">¥{{productInfo.originalPrice}}</text>
        <text class="sales">已售{{productInfo.sales}}件</text>
      </view>
      <view class="title">{{productInfo.title}}</view>
      <view class="desc">{{productInfo.description}}</view>
    </view>
    
    <!-- 商品规格 -->
    <view class="specs-section" @tap="showSpecsPopup">
      <text>选择：{{selectedSpecs || '请选择规格'}}</text>
      <text class="iconfont icon-arrow-right"></text>
    </view>
    
    <!-- 商品详情 -->
    <view class="detail-section">
      <view class="section-title">商品详情</view>
      <rich-text :nodes="productInfo.detail"></rich-text>
    </view>
    
    <!-- 底部操作栏 -->
    <view class="action-bar">
      <view class="left">
        <view class="icon-item" @tap="goHome">
          <text class="iconfont icon-home"></text>
          <text>首页</text>
        </view>
        <view class="icon-item" @tap="toggleFavorite">
          <text class="iconfont" :class="isFavorite ? 'icon-favorite-fill' : 'icon-favorite'"></text>
          <text>收藏</text>
        </view>
        <view class="icon-item" @tap="goCart">
          <text class="iconfont icon-cart"></text>
          <text>购物车</text>
        </view>
      </view>
      <view class="right">
        <button class="add-cart-btn" @tap="showSpecsPopup">加入购物车</button>
        <button class="buy-btn" @tap="showSpecsPopup">立即购买</button>
      </view>
    </view>
    
    <!-- 规格选择弹窗 -->
    <uni-popup ref="specsPopup" type="bottom">
      <view class="specs-popup">
        <view class="popup-header">
          <image :src="productInfo.images[0]" mode="aspectFill"></image>
          <view class="info">
            <text class="price">¥{{productInfo.price}}</text>
            <text class="stock">库存：{{productInfo.stock}}件</text>
          </view>
          <text class="close" @tap="closeSpecsPopup">×</text>
        </view>
        <view class="popup-content">
          <view class="specs-group" v-for="(group, index) in productInfo.specs" :key="index">
            <view class="group-title">{{group.name}}</view>
            <view class="specs-list">
              <text 
                class="specs-item" 
                v-for="(item, itemIndex) in group.values" 
                :key="itemIndex"
                :class="{ active: selectedSpecsMap[group.name] === item }"
                @tap="selectSpecs(group.name, item)"
              >{{item}}</text>
            </view>
          </view>
          <view class="quantity-section">
            <text>购买数量</text>
            <view class="quantity-control">
              <text class="minus" @tap="decreaseQuantity">-</text>
              <input type="number" v-model="quantity" />
              <text class="plus" @tap="increaseQuantity">+</text>
            </view>
          </view>
        </view>
        <view class="popup-footer">
          <button class="confirm-btn" @tap="confirmSpecs">确定</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { productApi, cartApi } from '@/api/index'
import { showToast, checkLogin } from '@/utils/common'

export default {
  data() {
    return {
      productInfo: {
        id: '',
        title: '',
        price: '',
        originalPrice: '',
        sales: 0,
        stock: 0,
        description: '',
        images: [],
        specs: [],
        detail: ''
      },
      selectedSpecsMap: {},
      selectedSpecs: '',
      quantity: 1,
      isFavorite: false,
      actionType: '' // 'cart' 或 'buy'
    }
  },
  onLoad(options) {
    const id = options.id
    this.getProductDetail(id)
  },
  methods: {
    // 获取商品详情
    async getProductDetail(id) {
      try {
        const res = await productApi.getProductDetail(id)
        this.productInfo = res
        // 检查是否已收藏
        this.checkFavoriteStatus(id)
      } catch (error) {
        showToast('商品详情加载失败')
      }
    },
    
    // 检查收藏状态
    async checkFavoriteStatus(id) {
      try {
        const res = await productApi.getFavoriteList()
        this.isFavorite = res.some(item => item.id === id)
      } catch (error) {
        console.error('获取收藏状态失败', error)
      }
    },
    
    // 显示规格选择弹窗
    showSpecsPopup() {
      if (!checkLogin()) return
      this.$refs.specsPopup.open()
    },
    
    // 关闭规格选择弹窗
    closeSpecsPopup() {
      this.$refs.specsPopup.close()
      this.resetSpecs()
    },
    
    // 选择规格
    selectSpecs(name, value) {
      this.selectedSpecsMap[name] = value
      this.selectedSpecs = Object.values(this.selectedSpecsMap).join('，')
    },
    
    // 增加数量
    increaseQuantity() {
      if (this.quantity < this.productInfo.stock) {
        this.quantity++
      }
    },
    
    // 减少数量
    decreaseQuantity() {
      if (this.quantity > 1) {
        this.quantity--
      }
    },
    
    // 重置规格选择
    resetSpecs() {
      this.selectedSpecsMap = {}
      this.selectedSpecs = ''
      this.quantity = 1
    },
    
    // 确认规格选择
    async confirmSpecs() {
      if (!this.selectedSpecs) {
        showToast('请选择规格')
        return
      }
      
      try {
        const data = {
          productId: this.productInfo.id,
          specs: this.selectedSpecsMap,
          quantity: this.quantity
        }
        
        if (this.actionType === 'cart') {
          await cartApi.addToCart(data)
          showToast('加入购物车成功')
        } else if (this.actionType === 'buy') {
          // 跳转到订单确认页
          uni.navigateTo({
            url: `/pages/order/confirm?productId=${this.productInfo.id}&specs=${JSON.stringify(this.selectedSpecsMap)}&quantity=${this.quantity}`
          })
        }
        
        this.closeSpecsPopup()
      } catch (error) {
        showToast('操作失败')
      }
    },
    
    // 切换收藏状态
    async toggleFavorite() {
      if (!checkLogin()) return
      
      try {
        if (this.isFavorite) {
          await productApi.unfavoriteProduct(this.productInfo.id)
          showToast('取消收藏成功')
        } else {
          await productApi.favoriteProduct(this.productInfo.id)
          showToast('收藏成功')
        }
        this.isFavorite = !this.isFavorite
      } catch (error) {
        showToast('操作失败')
      }
    },
    
    // 返回首页
    goHome() {
      uni.switchTab({
        url: '/pages/index/index'
      })
    },
    
    // 跳转购物车
    goCart() {
      uni.switchTab({
        url: '/pages/cart/cart'
      })
    }
  }
}
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 100rpx;
}

.product-swiper {
  height: 750rpx;
  
  image {
    width: 100%;
    height: 100%;
  }
}

.product-info {
  background: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;
  
  .price-section {
    margin-bottom: 20rpx;
    
    .price {
      font-size: 40rpx;
      color: #ff0000;
      font-weight: bold;
      margin-right: 20rpx;
    }
    
    .original-price {
      font-size: 28rpx;
      color: #999;
      text-decoration: line-through;
      margin-right: 20rpx;
    }
    
    .sales {
      font-size: 24rpx;
      color: #999;
    }
  }
  
  .title {
    font-size: 32rpx;
    color: #333;
    margin-bottom: 10rpx;
  }
  
  .desc {
    font-size: 28rpx;
    color: #666;
  }
}

.specs-section {
  background: #fff;
  padding: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  
  text {
    font-size: 28rpx;
    color: #333;
    
    &.icon-arrow-right {
      color: #999;
    }
  }
}

.detail-section {
  background: #fff;
  padding: 20rpx;
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
}

.action-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 100rpx;
  background: #fff;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  
  .left {
    display: flex;
    margin-right: 20rpx;
    
    .icon-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-right: 30rpx;
      
      .iconfont {
        font-size: 40rpx;
        color: #666;
        margin-bottom: 4rpx;
        
        &.icon-favorite-fill {
          color: #ff0000;
        }
      }
      
      text:last-child {
        font-size: 20rpx;
        color: #666;
      }
    }
  }
  
  .right {
    flex: 1;
    display: flex;
    
    button {
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      border-radius: 40rpx;
      margin-left: 20rpx;
      font-size: 28rpx;
      
      &.add-cart-btn {
        background: #ffd591;
        color: #ff0000;
      }
      
      &.buy-btn {
        background: #ff0000;
        color: #fff;
      }
    }
  }
}

.specs-popup {
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
  
  .popup-header {
    display: flex;
    padding: 20rpx;
    border-bottom: 1rpx solid #f5f5f5;
    
    image {
      width: 160rpx;
      height: 160rpx;
      border-radius: 8rpx;
      margin-right: 20rpx;
    }
    
    .info {
      flex: 1;
      
      .price {
        font-size: 36rpx;
        color: #ff0000;
        margin-bottom: 10rpx;
        display: block;
      }
      
      .stock {
        font-size: 24rpx;
        color: #999;
      }
    }
    
    .close {
      font-size: 40rpx;
      color: #999;
      padding: 20rpx;
    }
  }
  
  .popup-content {
    padding: 20rpx;
    max-height: 60vh;
    overflow-y: auto;
    
    .specs-group {
      margin-bottom: 30rpx;
      
      .group-title {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 20rpx;
      }
      
      .specs-list {
        display: flex;
        flex-wrap: wrap;
        
        .specs-item {
          padding: 10rpx 30rpx;
          border: 1rpx solid #ddd;
          border-radius: 30rpx;
          margin-right: 20rpx;
          margin-bottom: 20rpx;
          font-size: 24rpx;
          color: #333;
          
          &.active {
            background: #ff0000;
            color: #fff;
            border-color: #ff0000;
          }
        }
      }
    }
    
    .quantity-section {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      text {
        font-size: 28rpx;
        color: #333;
      }
      
      .quantity-control {
        display: flex;
        align-items: center;
        
        .minus, .plus {
          width: 60rpx;
          height: 60rpx;
          line-height: 60rpx;
          text-align: center;
          background: #f5f5f5;
          border-radius: 30rpx;
        }
        
        input {
          width: 80rpx;
          height: 60rpx;
          line-height: 60rpx;
          text-align: center;
          margin: 0 20rpx;
          background: #f5f5f5;
          border-radius: 8rpx;
        }
      }
    }
  }
  
  .popup-footer {
    padding: 20rpx;
    border-top: 1rpx solid #f5f5f5;
    
    .confirm-btn {
      width: 100%;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      background: #ff0000;
      color: #fff;
      border-radius: 40rpx;
      font-size: 28rpx;
    }
  }
}
</style> 
</style> 